package com.lq.fastnews.presenter;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lq.fastnews.iview.VideoView;
import com.lq.fastnews.model.api.ApiDefine;
import com.lq.fastnews.model.bean.video.VideoInfo;
import com.lq.fastnews.model.bean.video.VideoResult;
import com.lq.fastnews.model.subscribe.BaseSubsribe;
import com.lq.fastnews.model.subscribe.TaskSubsriber;
import com.lq.fastnews.utils.RxManager;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;

/**
 * Created by Administrator on 2016/7/12.
 */
public class VideoPresenter extends LoadPresenter <VideoView>{
    public void loadVideo(String city){
        addObservable(getApiService().queryVideo(ApiDefine.VIDEO_KEY, "json", city), new BaseSubsribe<VideoResult,VideoView>(mMvpView) {

            @Override
            public void onSuccess(VideoResult result) {
                if(result.error_code!=0){
                    mMvpView.showInfo(result.reason);
                    return;
                }
                RxManager.instance().add(Observable.create(new Observable.OnSubscribe<List<VideoInfo>>() {

                    @Override
                    public void call(Subscriber<? super List<VideoInfo>> subscriber) {
                        ArrayList<VideoInfo> infos = new ArrayList<>();
                        JsonArray datas = result.result.getAsJsonArray("data");
                        for (JsonElement e:datas){
                            JsonArray data = e.getAsJsonObject().getAsJsonArray("data");
                            for (JsonElement e1:data){
                                VideoInfo videoInfo = new Gson().fromJson(e1, VideoInfo.class);
                                JsonArray data1 = videoInfo.star.getAsJsonArray("data");
                                ArrayList<String> starName = new ArrayList<>();
                                ArrayList<String> starLine = new ArrayList<>();
                                for (JsonElement e2:data1){
                                    JsonObject o = e2.getAsJsonObject();
                                    starLine.add(o.get("line").getAsString());
                                    starName.add(o.get("name").getAsString());
                                }
                                videoInfo.starLine=starLine;
                                videoInfo.starName=starName;
                                infos.add(videoInfo);
                            }
                        }
                        subscriber.onNext(infos);

                    }
                }), new TaskSubsriber<List<VideoInfo>>() {

                    @Override
                    public void onNext(List<VideoInfo> videoInfos) {

                    }
                });
            }
        },true);

    }
}
